package com.dlc.shop.groupbuy.api.listener;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.event.CheckGroupOrderEvent;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.groupbuy.common.model.GroupOrder;
import com.dlc.shop.groupbuy.common.model.GroupTeam;
import com.dlc.shop.groupbuy.common.service.GroupOrderService;
import com.dlc.shop.groupbuy.common.service.GroupTeamService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 支付时校验订单过期事件
 *
 * @author lhd
 */
@Component("checkGroupOrderListener")
@AllArgsConstructor
public class CheckGroupOrderListener {

    private final GroupOrderService groupOrderService;
    private final GroupTeamService groupTeamService;

    @EventListener(CheckGroupOrderEvent.class)
    public void checkGroupOrderHandle(CheckGroupOrderEvent event) {

        String orderNumber = event.getOrder().getOrderNumber();
        GroupOrder groupOrder = groupOrderService.getOne(new LambdaQueryWrapper<GroupOrder>()
                .eq(GroupOrder::getOrderNumber, orderNumber));

        GroupTeam groupTeam = groupTeamService.getOne(new LambdaQueryWrapper<GroupTeam>()
                .eq(GroupTeam::getGroupTeamId, groupOrder.getGroupTeamId()));

        if (groupTeam.getEndTime() != null && System.currentTimeMillis() > groupTeam.getEndTime().getTime()) {
            //该拼团单不存在
            throw new YamiShopBindException("yami.group.order.no.exist");
        }
    }

}
